package com.cxh.rmsq.ui.activity.self

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.db.model.GroupEntity
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.activity.TitleBaseActivity
import com.cxh.rmsq.utils.RongGenerate
import com.cxh.rmsq.utils.loadImage
import com.xuexiang.xui.widget.imageview.RadiusImageView


class SelectOneGroupActivity : TitleBaseActivity() {

    private val recyclerView: RecyclerView by lazy { findViewById(R.id.recyclerView) }
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }
    private val mAdapter by lazy { AddFriendListAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_select_one_group)
        titleBar.tvTitle.text = "选择一个群聊"
        viewModel.getMyGroupList {
            recyclerView.layoutManager = LinearLayoutManager(this)
            recyclerView.adapter = mAdapter
            mAdapter.setNewInstance(it.data)
            mAdapter.setOnItemClickListener { adapter, view, position ->
                val intent = Intent()
                intent.putExtra(IntentExtra.LIST_STR_ID_LIST, mAdapter.data[position].id)
                intent.putExtra("groupName", mAdapter.data[position].name)
                setResult(RESULT_OK, intent)
                finish()
            }
        }
    }

    inner class AddFriendListAdapter :
        BaseQuickAdapter<GroupEntity, BaseViewHolder>(R.layout.item_common_sel_group),
        LoadMoreModule {

        override fun convert(holder: BaseViewHolder, item: GroupEntity) {
            with(holder) {
                setText(R.id.tv_name, item.name)
                var portraitUri: String? = item.portraitUri
                // 当没有头像时生成默认头像
                if (TextUtils.isEmpty(portraitUri)) {
                    portraitUri = RongGenerate.generateDefaultAvatar(
                        context, item.getId(), item.getName()
                    )
                }
                loadImage(portraitUri, getView<RadiusImageView>(R.id.riv_img))

            }
        }
    }
}
